package com.loop.unclelend.system.device.http

import com.loop.network.OkHttp
import com.loop.network.callback.StringCallback
import com.loop.network.model.Response
import com.loop.unclelend.utils.log.JsonFormat
import com.loop.unclelend.utils.log.UncleLog
import org.json.JSONObject
import java.util.function.Supplier

class ASPostAsyncTask(val url: String, val body: String, val taskId: String? = null) :
    Supplier<JSONObject> {

    override fun get(): JSONObject {
        return ASPostSyncTask(url = url, body = body, taskId = taskId).doPostAction()
    }
}

class ASPostSyncTask(val url: String, val body: String, val taskId: String? = null) {

    fun doPostAction(): JSONObject{
        if (this.url.isBlank() or this.body.isBlank()) return JSONObject().apply {
            put("taskId", taskId)
        }

        UncleLog.i("Device Url：  $url")
        UncleLog.i("Device Params： $body")

        OkHttp.post<String>(url) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .upJson(body)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    Thread { UncleLog.i("Device Response：${JsonFormat.format(response.body())}") }.start()
                }
                override fun onError(response: Response<String>) {
                }
                override fun onFinish() {
                }
            })
        return JSONObject().apply {
            put("taskId", taskId)
        }
    }
}